var app = getApp();
var wx4agency_api_url = app.globalData.wx4agency_api_url;
var applet_park_api_url_img = app.globalData.applet_park_api_url_img;

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/** 
* 时间戳转化为年 月 日 时 分 秒 
* number: 传入时间戳 
* format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
function formatTimeTwo(timestamp) {
  
  let date = new Date(timestamp);
  
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? ('0' + MM) : MM;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let m = date.getMinutes();
  m = m < 10 ? ('0' + m) : m;
  let s = date.getSeconds();
  s = s < 10 ? ('0' + s) : s;
  var str = y +'-'+MM+'-'+d+' '+h +':'+m+':'+s;
  
  return str;
}

function formatTime(date) {
  var year = new Date(date).getFullYear()
  var month = new Date(date).getMonth() + 1
  var day = new Date(date).getDate()
  var hour = new Date(date).getHours()
  var minute = new Date(date).getMinutes()
  var second = new Date(date).getSeconds();
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function ymdFormat(date) {
  var year = new Date(date).getFullYear()
  var month = new Date(date).getMonth() + 1
  var day = new Date(date).getDate()
  return [year, month, day].map(formatNumber).join('-')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function fetchURL(url, callback) {
  return fetch(url)
    .then(function(response) {
      if (response.status == 200) {
        return response.json();
      }
    }).then(function(data) {
      // 
      if (typeof callback == 'function') {
        callback(data);
      }
    })
}

function arrIndex(arr, element) {
  if (!element) {
    return -1;
  }
  for (var i in arr) {
    if (element == arr[i]) {
      return i;
    }
  }
  return -1;
}

function dx(n) {
  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
    return "数据非法";
  var unit = "千百拾亿千百拾万千百拾元角分",
    str = "";
  n += "00";
  var p = n.indexOf('.');
  if (p >= 0)
    n = n.substring(0, p) + n.substr(p + 1, 2);
  unit = unit.substr(unit.length - n.length);
  for (var i = 0; i < n.length; i++)
    str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
  return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}

function showModal(toastContent) {
  // 
  // var pages = getCurrentPages();
  // var currPage = pages[pages.length - 1]; //上一个页面,是车辆编辑页
  //
  // 
  // currPage.setData({toastContent:toastContent});
  // currPage.setData({showToast:1});
  //  timer = setTimeout(function () {
  //       hideModal();
  // }, 2000);
  //新方法
  wx.showToast({
    title: toastContent,
    icon: 'none',
    duration: 2500
  });
}

function hideModal() {
  var pages = getCurrentPages();
  var currPage = pages[pages.length - 1]; //上一个页面,是车辆编辑页
  currPage.setData({
    showToast: 0
  });
}

function checkStaffRight(token, rightCode, callback) {
  if (!token) {
    callback(false);
    return;
  }
  if (!rightCode) {
    callback(false);
    return;
  }
  wx.request({
    url: wx4agency_api_url + '/wechatapp/checkStaffRight?token=' + token + '&rightCode=' + rightCode,
    success: function(res) {
      if (res.data.success && res.data.data.hasRight) {
        callback(true);
      } else {
        callback(false);
      }
      return;
    },
    fail: function() {
      callback(false);
      return;
    }
  })
}

function checkVIN(vin) {
  if (!vin) {
    return false;
  }
  var vinMapWeighting = new Map();
  var vinMapValue = new Map();
  vinMapWeighting.set(1, 8);
  vinMapWeighting.set(2, 7);
  vinMapWeighting.set(3, 6);
  vinMapWeighting.set(4, 5);
  vinMapWeighting.set(5, 4);
  vinMapWeighting.set(6, 3);
  vinMapWeighting.set(7, 2);
  vinMapWeighting.set(8, 10);
  vinMapWeighting.set(9, 0);
  vinMapWeighting.set(10, 9);
  vinMapWeighting.set(11, 8);
  vinMapWeighting.set(12, 7);
  vinMapWeighting.set(13, 6);
  vinMapWeighting.set(14, 5);
  vinMapWeighting.set(15, 4);
  vinMapWeighting.set(16, 3);
  vinMapWeighting.set(17, 2);

  vinMapValue.set('0', 0);
  vinMapValue.set('1', 1);
  vinMapValue.set('2', 2);
  vinMapValue.set('3', 3);
  vinMapValue.set('4', 4);
  vinMapValue.set('5', 5);
  vinMapValue.set('6', 6);
  vinMapValue.set('7', 7);
  vinMapValue.set('8', 8);
  vinMapValue.set('9', 9);
  vinMapValue.set('A', 1);
  vinMapValue.set('B', 2);
  vinMapValue.set('C', 3);
  vinMapValue.set('D', 4);
  vinMapValue.set('E', 5);
  vinMapValue.set('F', 6);
  vinMapValue.set('G', 7);
  vinMapValue.set('H', 8);
  vinMapValue.set('J', 1);
  vinMapValue.set('K', 2);
  vinMapValue.set('M', 4);
  vinMapValue.set('L', 3);
  vinMapValue.set('N', 5);
  vinMapValue.set('P', 7);
  vinMapValue.set('R', 9);
  vinMapValue.set('S', 2);
  vinMapValue.set('T', 3);
  vinMapValue.set('U', 4);
  vinMapValue.set('V', 5);
  vinMapValue.set('W', 6);
  vinMapValue.set('X', 7);
  vinMapValue.set('Y', 8);
  vinMapValue.set('Z', 9);

  var uppervin = vin.toUpperCase();
  //排除字母O、I
  if (uppervin.indexOf("O") >= 0 || uppervin.indexOf("I") >= 0) {
    reultFlag = false;
  } else {
    //1:长度为17
    if (vin.length == 17) {
      var vinArr = uppervin.split('');
      var amount = 0;
      for (var i = 0; i < vinArr.length; i++) {
        //VIN码从从第一位开始，码数字的对应值×该位的加权值，计算全部17位的乘积值相加
        amount += vinMapValue.get(vinArr[i]) * vinMapWeighting.get(i + 1);
      }
      return true;
      //乘积值相加除以11、若余数为10，即为字母Ｘ
      // if (amount % 11 == 10) {
      //   if (vinArr[8] == 'X') {
      //     reultFlag = true;
      //   } else {
      //     reultFlag = false;
      //   }
      //
      // } else {
      //   //VIN码从从第一位开始，码数字的对应值×该位的加权值，
      //   //                    计算全部17位的乘积值相加除以11，所得的余数，即为第九位校验值
      //   if (amount % 11 != vinMapValue.get(vinArr[8])) {
      //     reultFlag = false;
      //   } else {
      //     reultFlag = true;
      //   }
      // }
    } else {
      reultFlag = false;
    }
  }
  return reultFlag;
}

function sleep(delay) {
  var start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}
function Handleimg(e) {
  let imglist = e.split(",")[0];
  let imglists = [];
  let url = applet_park_api_url_img;
  for (let item of imglist) {

    let list = url + item
    imglists.push(list);
  }

  return imglists
}
function showLoading(message) {
  if (wx.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.showLoading({
      title: message,
      mask: true
    });
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    wx.showToast({
      title: message,
      icon: 'loading',
      mask: true,
      duration: 20000
    });
  }
}
function hideLoading() {
  if (wx.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
    wx.hideLoading();
  } else {
    wx.hideToast();
  }
}

function getDates(days, todate) {
  var dateArry = [];
  for (var i = 0; i < days; i++) {
    var dateObj = dateLater(todate, i);
    dateArry.push(dateObj)
  }
  return dateArry;
}

function dateLater(dates, later) {
  let dateObj = {};
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let date = new Date(dates);
  date.setDate(date.getDate() + later);
  let day = date.getDay();
  let yearDate = date.getFullYear();
  let month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  let dayFormate = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  dateObj.time =  yearDate+'-'+ month + '-' + dayFormate;
  dateObj.week = show_day[day];
  return dateObj;
}

module.exports = {
  formatTime: formatTime,
  formatNumber: formatNumber,
  fetch: fetchURL,
  arrIndex: arrIndex,
  showModal: showModal,
  ymdFormat: ymdFormat,
  checkStaffRight: checkStaffRight,
  checkVIN: checkVIN,
  dx: dx,
  sleep: sleep,
  Handleimg: Handleimg,
  showLoading: showLoading,
  hideLoading: hideLoading,
  formatTime: formatTime,
  formatTimeTwo: formatTimeTwo,
  getDates: getDates
}


